import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import bundleManager from '@ohos.bundle.bundleManager';
import promptAction from '@ohos.promptAction';
import common from '@ohos.app.ability.common';
/**
 * 动态申请权限工具类
 */
export class AccessPermissionHelper {
  private readonly TAG: string = 'AccessPermissionHelper';
  /**
   * 动态审核状态码
   * 1000：默认值。未开始查询权限
   * 1001：查询完成，已授权
   * 1002：查询完成，未授权
   */
  statusCode: number = 1000
  private pContext: common.UIAbilityContext
  PERMISSION_READ_MEDIA: Array<Permissions> = ['ohos.permission.READ_MEDIA'];
  PERMISSION_CAMERA: Array<Permissions> = ['ohos.permission.CAMERA'];
  PERMISSION_LOCATION: Array<Permissions> = ['ohos.permission.LOCATION'];
  PERMISSION_APPROXIMATELY_LOCATION: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION']

  constructor(context: common.UIAbilityContext) {
    this.pContext = context;
  }

  /**
   * 获取当前token授权列表
   */
  public async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager = abilityAccessCtrl.createAtManager();
    let grantStatus: abilityAccessCtrl.GrantStatus;

    // 获取应用程序的accessTokenID
    let tokenId: number;
    try {
      let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
      let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
      tokenId = appInfo.accessTokenId;
    } catch (err) {
      console.error(this.TAG, `getBundleInfoForSelf failed, code is ${err.code}, message is ${err.message}`);
    }

    // 校验应用是否被授予权限
    try {
      grantStatus = await atManager.checkAccessToken(tokenId, permission);
    } catch (err) {
      console.error(this.TAG, `checkAccessToken failed, code is ${err.code}, message is ${err.message}`);
    }

    return grantStatus;
  }

  /**
   * 检查是否有这个权限
   */
  async checkPermissions(permission: Array<Permissions>): Promise<void> {
    //context用下面这个语句在ets的函数中取得。
    // let context = getContext(this) as common.UIAbilityContext;
    // let permissions = PERMISSION_READ_MEDIA

    let grantStatus: abilityAccessCtrl.GrantStatus = await this.checkAccessToken(permission[0]);

    if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
      // 已经授权，可以继续访问目标操作
      this.statusCode = 1001
      console.log(this.TAG, 'statusCode:' + this.statusCode)

    } else {
      // 申请相册权限
      this.reqPermissionsFormUser(permission);
    }
  }

  reqPermissionsFormUser(permission: Array<Permissions>) {
    // let context = getContext(this) as common.UIAbilityContext;
    let context = this.pContext as common.UIAbilityContext;
    let atManager = abilityAccessCtrl.createAtManager();

    // requestPermissionsFromUser：判断权限的授权状态来决定是否唤起弹窗
    atManager.requestPermissionsFromUser(context, permission).then((data) => {
      let grantStatus: Array<number> = data.authResults;
      let length: number = grantStatus.length;
      for (let i = 0;i < length; i++) {
        if (grantStatus[i] === 0) {
          // 用户授权，可以继续访问目标操作
          this.statusCode = 1001
          console.log(this.TAG, 'statusCode:' + this.statusCode)

        } else {
          // 用户拒绝授权，提示用户必须授权才能访问当前页面的功能
          this.statusCode = 1002
          console.log(this.TAG, 'statusCode:' + this.statusCode)
          promptAction.showToast({ message: '授权失败！' })
        }
      }
    }).catch((err) => {
      console.error(this.TAG, `requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
    })
  }
}

//定义权限枚举，方便引用
enum permissionList {
  PERMISSION_READ_MEDIA = 'ohos.permission.READ_MEDIA',
  PERMISSION_CAMERA = 'ohos.permission.CAMERA'

}